package com.yamaha.bikemarket;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

public class MainActivity extends AMyActivity implements
		AdapterView.OnItemClickListener {

	private ImageLoader imageLoader;
	private static final AsyncHttpClient client = new AsyncHttpClient();
	private final FeedItemAdapter adapter = new FeedItemAdapter();
	private final List<JSONObject> list = new ArrayList<JSONObject>();
	private LayoutInflater inflater;

	private final String TAG = "BikeMarketMainActivity";

	private int index, top;

	// Filter
	private String filterType;
	private String filterParams;

	public MainActivity() {
		super(MenuType.NONE);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		filterType = getIntent().getStringExtra("filterType");
		filterParams = getIntent().getStringExtra("filterParams");

		inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

		final DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory().cacheOnDisc().build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext()).defaultDisplayImageOptions(
				defaultOptions).build();
		if (null != imageLoader && imageLoader.isInited()) {
			imageLoader.destroy();
			imageLoader = null;
		}
		imageLoader = ImageLoader.getInstance();
		if (!imageLoader.isInited()) {
			imageLoader.init(config);
		}

		setListenerForMenu();

		final ListView listView = (ListView) findViewById(R.id.feed_list);
		listView.setAdapter(adapter);

		boolean pauseOnScroll = true; // or true
		boolean pauseOnFling = true; // or false
		PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
				pauseOnScroll, pauseOnFling);
		listView.setOnScrollListener(listener);
		listView.setClickable(true);
		listView.setOnItemClickListener(this);
		adapter.setLoading(true);

		getData();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		final ListView listView = (ListView) findViewById(R.id.feed_list);

		final int index = listView.getFirstVisiblePosition();
		final View v = listView.getChildAt(0);
		final int top = (v == null) ? 0 : v.getTop();

		outState.putInt("ListViewIndex", index);
		outState.putInt("ListViewTop", top);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		if (savedInstanceState != null) {
			final ListView listView = (ListView) findViewById(R.id.feed_list);
			index = savedInstanceState.getInt("ListViewIndex");
			top = savedInstanceState.getInt("ListViewTop");

			listView.setSelectionFromTop(index, top);
		}
	}

	@Override
	protected List<EditText> getEditTexts() {
		return null;
	}

	public ImageLoader getImageLoader() {
		return imageLoader;
	}

	private void moveToBack(View myCurrentView) {
		ViewGroup myViewGroup = ((ViewGroup) myCurrentView.getParent());
		int index = myViewGroup.indexOfChild(myCurrentView);
		for (int i = 0; i < index; i++) {
			myViewGroup.bringChildToFront(myViewGroup.getChildAt(i));
		}
	}

	@Override
	public void onClick(View v) {

		if (onMenuClick(v)) {
			return;
		}
	}

	private static class ItemHolder {
		ImageView feed_bg;
		ImageView feed_image;
		TextView username;
		TextView postTime;
		TextView feed_brand;
		TextView feed_model;
		TextView price;
	}

	private final class FeedItemAdapter extends BaseAdapter {

		private boolean isLoading = true;

		public void setLoading(boolean isLoading) {
			this.isLoading = isLoading;
		}

		@Override
		public int getCount() {
			return (isLoading) ? 1 : list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (isLoading) {
				convertView = inflater.inflate(R.layout.loading_item, parent,
						false);
				convertView.setId(0x0123);
				return convertView;
			}

			if (convertView != null && convertView.getId() == 0x0123) {
				convertView = null;
			}

			ItemHolder holder;
			if (null == convertView) {
				convertView = inflater.inflate(R.layout.feed_item_layout,
						parent, false);
				convertView.setId(0x124 + position);
				holder = new ItemHolder();
				holder.feed_bg = (ImageView) convertView
						.findViewById(R.id.feed_bg);
				holder.feed_image = (ImageView) convertView
						.findViewById(R.id.feed_image);
				holder.username = (TextView) convertView
						.findViewById(R.id.feed_user);
				holder.postTime = (TextView) convertView
						.findViewById(R.id.feed_post_time);
				holder.feed_brand = (TextView) convertView
						.findViewById(R.id.feed_brand);
				holder.feed_model = (TextView) convertView
						.findViewById(R.id.feed_model);
				holder.price = (TextView) convertView
						.findViewById(R.id.feed_price);

				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}

			holder.feed_bg.setImageBitmap(null);
			if (position % 2 == 1) {
				holder.feed_bg.setBackgroundResource(R.drawable.cellbg_blue);
			} else {
				holder.feed_bg.setBackgroundResource(R.drawable.cellbg_pink);
			}

			try {
				final JSONObject obj = list.get(position);

				//
				holder.feed_brand.setText("Brand : "
						+ obj.getString("brand_name"));
				holder.feed_model.setText("Model : "
						+ obj.getString("model_name"));
				holder.price.setText("Price : " + obj.getString("price")
						+ " baht");
				holder.username.setText(obj.getString("user_name"));
				holder.postTime.setText(obj.getString("time"));

				final JSONArray pix = obj.getJSONArray("pix");

				holder.feed_image.setImageBitmap(null);
				if (null != pix && pix.length() > 0) {
					final String url = pix.getString(0);

					if (url != null && url.length() > 0) {
						imageLoader.displayImage(url, holder.feed_image);
					}
				}

			} catch (JSONException e) {
				LogUtil.e("Get View", e.getMessage(), e);
			}

			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

		if (adapter.isLoading) {
			return;
		}

		final JSONObject item = (JSONObject) adapter.getItem(position);

		if (item != null && v.getId() != 0x0123) {

			LogUtil.i("MainActivity", "onItemClick Position : " + position);
			LogUtil.i("MainActivity", "Item : " + item.toString());

			final Intent intent = new Intent(this, BikeDetailFragment.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			intent.putExtra("item", item.toString());
			startActivity(intent);
		} else {
			LogUtil.w("MainActivity", "Detail Item is NULL.");
			Toast.makeText(this, "Something error", Toast.LENGTH_SHORT).show();
		}
	}

	private void getData() {

		list.clear();

		final String userId = SCStaticFunc.getUserId(this);

		final RequestParams params = new RequestParams();
		params.put("user_id", userId);

		if (null != filterType) {

			LogUtil.i("MainActivity", "Filter Type : " + filterType);
			LogUtil.i("MainActivity", "Filter Param : " + filterParams);

			if ("PROVINCE".equals(filterType)) {

				if (null != filterParams) {
					params.put("type", filterType);

					try {
						final JSONArray array = new JSONArray(filterParams);
						final ArrayList<String> model = new ArrayList<String>();
						for (int i = 0; i < array.length(); i++) {
							model.add(array.getString(i));
						}
						params.put("province[]", model);

					} catch (JSONException e) {
						LogUtil.e("MainActivity", "Param : " + e.getMessage(),
								e);
					}
				}

			} else if ("MODEL_LIST".equals(filterType)) {

				if (null != filterParams) {
					params.put("type", filterType);

					try {
						final JSONArray array = new JSONArray(filterParams);
						final ArrayList<String> model = new ArrayList<String>();
						for (int i = 0; i < array.length(); i++) {
							model.add(array.getString(i));
						}
						params.put("model[]", model);

					} catch (JSONException e) {
						LogUtil.e("MainActivity", "Param : " + e.getMessage(),
								e);
					}
				}

			} else if ("REG_YEAR".equals(filterType)) {
				if (null != filterParams) {
					params.put("type", filterType);

					try {
						final JSONArray array = new JSONArray(filterParams);
						final ArrayList<String> model = new ArrayList<String>();
						for (int i = 0; i < array.length(); i++) {
							model.add(array.getString(i));
						}
						params.put("model[]", model);

					} catch (JSONException e) {
						LogUtil.e("MainActivity", "Param : " + e.getMessage(),
								e);
					}
				}
			} else {
				params.put("type", filterType);
			}
		}

		LogUtil.i("MainActivity", "Param : " + params.toString());

		client.post(API.GET_SHOW_ALL_BIKE, params,
				new MyAsyncHttpResponseHandler(API.GET_SHOW_ALL_BIKE, this) {

					@Override
					public void onSuccess(final String res) {
						super.onSuccess(res);

						try {
							final JSONObject object = new JSONObject(res);

							final boolean isSuccess = object
									.getBoolean("success");
							if (isSuccess) {

								final JSONArray resList = object
										.getJSONArray("message");

								// Convert To java.util.List
								for (int i = 0; i < resList.length(); i++) {
									list.add(resList.getJSONObject(i));
								}

								adapter.setLoading(false);
								adapter.notifyDataSetChanged();

								// final ListView listView = (ListView)
								// findViewById(R.id.feed_list);
								// listView.setSelectionFromTop(index, top);

							} else {
								final String msg = object.getString("message");
								Utils.showAlertDialog(MainActivity.this,
										"Error", msg);
							}

						} catch (JSONException e) {
							LogUtil.e(TAG, e.getMessage(), e);
						}

					}

				});
	}
}
